import Vue from 'vue';
import Vuex from 'vuex';
import ls from '../utils/localStorage';
import {setCookie, delCookie, getCookie} from '../utils/cookie';
import {SD_TOKEN, SD_USER_INFO, SD_AUTH} from '../common/keys';

Vue.use(Vuex)

// store 驱动应用的数据源 
// Mutation 提交修改store状态 
const state = {
    user: ls.getItem(SD_USER_INFO),

    auth: ls.get(SD_AUTH)
}

const mutations = {
    UPDATE_USER(state, user) {
        state.user = user.user_info
        state.auth = true
        ls.setItem(SD_USER_INFO, user.user_info)
        ls.set(SD_AUTH, true)
        setCookie(SD_TOKEN, user.token.access_token, { expires: 2 })
    },
    DELETE_USER(state) {
        state.user = null
        ls.clearAll()
        delCookie(SD_TOKEN)
    },
    UPDATE_USERTOKEN(state, usertoken) {
        setCookie(SD_TOKEN, usertoken.access_token, { expires: 2 })
    }
}
const actions = {
    login({commit}, user) {
        commit('UPDATE_USER', user)
    },
    update_usertoken({commit}, user_token) {
        commit('UPDATE_USERTOKEN', user_token)
    },
    logout({commit}){
        commit('DELETE_USER')
    }
}

export default new Vuex.Store({
    state,
    mutations,
    actions
})